const db = uniCloud.database()
const dbCmd = db.command
const defaultOptions = {
	table:"",
	attr:"",
	id: "",
	value: 1
}
module.exports = {
	_before: function() { // 通用预处理器

	},

	async opration(options = defaultOptions) {
		const newOptions = Object.assign(defaultOptions,options)
		if (!newOptions.id || !newOptions.table || !newOptions.attr || !newOptions.value || typeof newOptions.value !== 'number') {
			return {
				errCode: "utilObj-opration-error",
				errMsg: '参数错误'
			}
		}
		let attr = newOptions.attr
		try{
			return await db.collection(newOptions.table).doc(newOptions.id).update({
				[attr]: dbCmd.inc(newOptions.value)
			})
		}catch(e){
			return {
				errCode: "utilObj-opration-server-error",
				errMsg: e.message
			}
		}
		
	},
	
	async getList(type,skip = 0){
		let collection = []
		let where = ""
		let field = ""
		let orderBy = ""
		
		
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		
		try{
			if(type == "content"){
				where = "user_id == $cloudEnv_uid && article_status == 1"
			}else{
				where = "article_status == 1"
			}
			
			const blogList = await dbJQL.collection("blog")
			.where(where)
			.field("_id,title,publish_date")
			.orderBy("publish_date desc,_id desc")
			.skip(skip)
			.limit(20)
			.get()
			if(type == "content") return blogList.data
			
			const blogIndexList = blogList.data.map(b => b._id + '')
			if(!blogIndexList.length) return []
			let result = []
			
			if(type == "like"){
				where = `user_id == $cloudEnv_uid && article_id in ['${blogIndexList.join("','")}'] && like_status == 0`
				result = await dbJQL.collection("blog-like")
				.where(where)
				.field('article_id,date,_id')
				.orderBy('date desc,_id desc')
				.skip(skip)
				.limit(20)
				.get()
			}else {
				where = `user_id == $cloudEnv_uid && article_id in ['${blogIndexList.join("','")}']`
				result = await dbJQL.collection("blog-comment")
				.where(where)
				.groupBy('article_id')
				.groupField('count(*) as count')
				.skip(skip)
				.limit(20)
				.get()
			}
	
			result.data.forEach((i,c) => {
				const index = blogIndexList.findIndex(f => f == i.article_id)
				if(index == -1) return   
				result.data[c] = Object.assign({},result.data[c],blogList.data[index])
			})
			
			return result.data
		}catch(e){
			//TODO handle the exception
			return e
		}
	}

}


